package sink

import (
	"database/sql"
	"fmt"
	"gomuisc/models/mysql"
)
func(sink MysqlSink) GetSingleList(page int,pagesize int,keyword string)(result []map[string]string,err error ){
	//rows,err = sink.database.Query("select * from m_single where song_name like '%?%' limit ?,?", keyword,page,pagesize)
	rows,err := sink.database.Query("select id,song_id,song_name,singer,album,duration,sheet_id  from m_single where song_name like ? limit ?,?", "%" + keyword + "%",page*pagesize,pagesize)
	//rows,err := sink.database.Query("select id,song_name,singer,album,duration,sheet_id from m_single where id>?",1)

	//err := sink.database.QueryRow("SELECT song_name,singer,album FROM m_single WHERE id >?", 1).Scan(&song_name, &singer, &album)
	if err != nil {
		fmt.Println("exec failed, ", err)
		return
	}
	//读出查询出的列字段名
	cols, _ := rows.Columns()
	//values是每个列的值，这里获取到byte里
	values := make([][]byte, len(cols))
	//query.Scan的参数，因为每次查询出来的列是不定长的，用len(cols)定住当次查询的长度
	scans := make([]interface{}, len(cols))
	//让每一行数据都填充到[][]byte里面
	for i := range values {
		scans[i] = &values[i]
	}

	var results []map[string]string
	i:= 0
	for rows.Next() {
		if err = rows.Scan(scans...); err != nil { //query.Scan查询出来的不定长值放到scans[i] = &values[i],也就是每行都放在values里
			fmt.Println(err)
			return
		}
		row := make(map[string]string) //每行数据

		for k, v := range values { //每行数据是放在values里面，现在把它挪到row里
			key := cols[k]
			row[key] = string(v)
		}
		fmt.Println("结果集",row)
		results = append(results,row)
		i++
	}
	//查询出来的数组
	for k, v := range results {
		fmt.Println(k, v)
	}
	return results,nil
}
func (sink MysqlSink) InsertSingle(single mysql.Single) (err error) {
	var song_id  int
	err = sink.database.QueryRow("select song_id from m_single where song_id = ? ",
		single.Song_id).Scan(&song_id)
	if err == sql.ErrNoRows {
		_, err = sink.database.Exec("insert into m_single(song_id,song_name,singer,album,duration,sheet_id) values (?,?,?,?,?,?)",
			single.Song_id, single.Song_name,single.Singer,single.Album,single.Duration,single.Sheet_id)
		if err != nil {
			return
		}
		//err = sink.InsertYunyinyueUser(comment.User)
		return
	}
	return nil
}